<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller;

use app\common\model\AdminUser;
use app\service\user\UserCommonService;

class Login extends Base
{
    protected $noLoginAction = ['login', 'getBackgroundImage'];

    /**
     * Login background image
     */
    public function getBackgroundImage()
    {
        $data['url'] = conf('admin_login_bg');
        $this->success('', $data);
    }

    /**
     * Administrator login
     */
    public function login()
    {
        // Administrator login
        $data     = $this->request->post();
        $validate = new \app\adminapi\validate\LoginValidate;
        $validate->failException(true)->check($data);
        $user = AdminUser::where('username', $data['username'])->findOrEmpty();
        $user->isEmpty() && throw new \Exception(trans('member_not_exists'));
        password_verify($data['password'], $user->password) || throw new \Exception(trans('password_incorrect'));

        $token = (new UserCommonService())->createToken($user->toArray(), 'admin');
        $data  = array_merge($user->toArray(), $token);
        $this->success(trans('login_successful'), $data);
    }

}